// src/api/dealerService.js
import request from '@/utils/request'

const DealerService = {
  // 获取所有经销商
  getAllDealers(type = '') {
    const params = type ? { type } : {};
    console.log('DealerService: Fetching dealers with params:', params);
    
    return request({
      url: '/dealers',
      method: 'get',
      params
    }).then(response => {
      console.log('DealerService: Received response:', response);
      if (!response.data) {
        throw new Error('No data received from server');
      }
      return response;
    }).catch(error => {
      console.error('DealerService: Error fetching dealers:', error.response?.data || error);
      throw error;
    });
  },

  // 添加经销商
  addDealer(dealer) {
    console.log('DealerService: Adding dealer:', dealer)
    return request({
      url: '/dealers',
      method: 'post',
      data: dealer
    }).catch(error => {
      console.error('DealerService: Error adding dealer:', error.response?.data || error)
      throw error
    })
  },

  // 更新经销商
  updateDealer(id, dealer) {
    console.log('DealerService: Updating dealer:', id, dealer)
    return request({
      url: `/dealers/${id}`,
      method: 'put',
      data: dealer
    }).catch(error => {
      console.error('DealerService: Error updating dealer:', error.response?.data || error)
      throw error
    })
  },

  // 删除经销商
  deleteDealer(id) {
    console.log('DealerService: Deleting dealer:', id)
    return request({
      url: `/dealers/${id}`,
      method: 'delete'
    }).catch(error => {
      console.error('DealerService: Error deleting dealer:', error.response?.data || error)
      throw error
    })
  }
}

export default DealerService
